package com.southwind.demo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class Test {
    public static void main(String[] args) {
        TimeLock timeLock = new TimeLock();
        /**
         * A 拿到锁，执行业务代码，休眠 5 秒钟
         * B 尝试拿锁，需要在 3 秒钟之内拿到锁
         */
        new Thread(()->{
            timeLock.lock();
        },"A").start();
        new Thread(()->{
            timeLock.lock();
        },"B").start();
    }
}

class TimeLock{

    private ReentrantLock reentrantLock = new ReentrantLock();

    public void lock(){
        /**
         * 尝试在3S内获取锁
         */
        try {
            if(reentrantLock.tryLock(3, TimeUnit.SECONDS)){
                System.out.println(Thread.currentThread().getName()+" get lock");
                TimeUnit.SECONDS.sleep(5);
            }else{
                System.out.println(Thread.currentThread().getName()+" not lock");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if(reentrantLock.isHeldByCurrentThread()){
                reentrantLock.unlock();
            }
        }
    }
}
